package us.sunrisemorning.pixivbrower.spider;

import java.util.ArrayList;
import java.util.List;

public class SpiderService implements SpiderCallback {

    private List<String> queue = new ArrayList<String>();

    private PixivSpider currentSpider = null;

    public void addKeyword(String keyword) {
        queue.add(keyword);
        next();
    }

    public synchronized void removeKeyword(int index) {
        if (queue.size() > index) {
            queue.remove(index);
        }
    }

    public synchronized void next() {
        if (currentSpider == null && queue.size() > 0) {
            String keyword = queue.remove(0);
            PixivSpider spider = new PixivSpider(keyword, this);
            currentSpider = spider;

            new Thread(spider).start();
        }
    }

    public synchronized void stop() {
        if (currentSpider != null) {
            currentSpider.stop();
        }
    }

    public List<String> getQueueInformation() {
        List<String> result = new ArrayList<String>();
        if (currentSpider != null) {
            result.add(currentSpider.getKeyword());
        }
        result.addAll(queue);
        return result;
    }

    public SpiderStatus getStatus() {
        if (currentSpider != null) {
            return currentSpider.getStatus();
        }
        return null;
    }

    @Override
    public void callback() {
        currentSpider = null;
        next();
    }
}
